package com.jrx.anytxn.accounting.job.consolidationbilling.config;

import com.jrx.anytxn.accounting.bean.BillingBean;
import com.jrx.anytxn.accounting.bean.DealBillBean;
import com.jrx.anytxn.accounting.config.AnytxnBatchProperties;
import com.jrx.anytxn.accounting.config.PathConfig;
import com.jrx.anytxn.accounting.entity.GaVoucherInfo;
import com.jrx.anytxn.accounting.job.consolidationbilling.step.ConsolidationBillingListener;
import com.jrx.anytxn.accounting.job.consolidationbilling.step.ConsolidationBillingWriter;
import com.jrx.anytxn.accounting.mapper.base.GaSubjectDetailTransitionMapper;
import com.jrx.anytxn.accounting.service.IConsolidationService;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 并账处理
 *
 * @author Qingyao Xing
 * @date 2019/9/9 13:28
 */
@Configuration
@EnableConfigurationProperties({AnytxnBatchProperties.class, PathConfig.class})
public class ConsolidationBillingConfiguration {

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private IOrganizationTableService organizationTableService;

    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;

    @Autowired
    private IConsolidationService iConsolidationService;

    @Autowired
    public PathConfig pathConfig;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Resource
    private GaSubjectDetailTransitionMapper gaSubjectDetailTransitionMapper;

    private Map<String, DealBillBean> subjectDetailMap = new ConcurrentHashMap<>();


    @Bean
    public Job billingJob() {
        return jobBuilderFactory.get("billingJob")
                .listener(billingJobExecutionListener())
                .start(billingStep())
                .next(billingInsertStep())
                .build();
    }

    @Bean
    public Step billingStep() {
        return stepBuilderFactory.get("billingStep")
                .<GaVoucherInfo, GaVoucherInfo>chunk(anytxnBatchProperties.getBillingConfiguration().getChunkLimit())//表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(billingReader())
                .writer(consolidationBillingWriter())
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getBillingConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    public ItemWriter<? super GaVoucherInfo> consolidationBillingWriter() {
        return new ConsolidationBillingWriter(subjectDetailMap);
    }

    @Bean
    public Step billingInsertStep() {
        return stepBuilderFactory.get("billingInsertStep")
                .tasklet(billingTasklet())
                .build();
    }


    @Bean
    @StepScope
    public SynchronizedItemStreamReader<GaVoucherInfo> billingReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
        Date businessDate = org.getToday();
        MyBatisCursorItemReader<GaVoucherInfo> billingCursorReader = new MyBatisCursorItemReader<>();
        billingCursorReader.setSaveState(false);
        billingCursorReader.setSqlSessionFactory(sqlSessionFactory);
        billingCursorReader.setQueryId("com.jrx.anytxn.accounting.mapper.ext.ExtVoucherInfoMapper.selectVoucherByDateForBillingBatch");
        Map<String, Object> map = new HashMap<>();
        map.put("businessDate",businessDate);
        billingCursorReader.setParameterValues(map);
        //同步reader   线程安全
        SynchronizedItemStreamReader<GaVoucherInfo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(billingCursorReader);
        return synchronizedItemStreamReader;
    }



    @Bean
    public Tasklet billingTasklet() {
        return (stepContribution, chunkContext) -> {
            BillingBean billingBean = iConsolidationService.getBillingBean(subjectDetailMap, pathConfig.getBatchTaskId());
            if (CollectionUtils.isNotEmpty(billingBean.getInsertSubjectDetailTransitionList())) {
                billingBean.getInsertSubjectDetailTransitionList().forEach(info -> gaSubjectDetailTransitionMapper.insertSelective(info));
            }
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    public JobExecutionListener billingJobExecutionListener() {
        return new ConsolidationBillingListener(subjectDetailMap);
    }
}
